package com.cw.lang.common.framework.handle;

import org.springframework.core.MethodParameter;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.cw.lang.common.annotation.JsonArgument;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author chenw
 * @version $$Id: JsonArgumentRequestMappingHandler.java, v 0.1 2018/10/20 7:17 PM chenw Exp $$
 */
public class JsonArgumentRequestMappingHandler implements HandlerMethodArgumentResolver {

    private static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean supportsParameter(@NonNull MethodParameter parameter) {
        return parameter.hasParameterAnnotation(JsonArgument.class);
    }

    @Override
    public Object resolveArgument(@NonNull MethodParameter parameter, ModelAndViewContainer mavContainer,
        @NonNull NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        JsonArgument jsonArgument = parameter.getParameterAnnotation(JsonArgument.class);
        if (jsonArgument == null) {
            throw new IllegalArgumentException("@JsonArgument can't be null!");
        }
        String json = webRequest.getParameter(jsonArgument.value());
        return objectMapper.readValue(json, parameter.getParameterType());
    }
}
